package com.jiawa.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.wiki.domain.Category;
import com.jiawa.wiki.domain.CategoryExample;
import com.jiawa.wiki.mapper.CategoryMapper;
import com.jiawa.wiki.req.CategoryQueryReq;
import com.jiawa.wiki.req.CategorySaveReq;
import com.jiawa.wiki.resp.CategoryQueryResp;
import com.jiawa.wiki.resp.PageResp;
import com.jiawa.wiki.util.CopyUtil;
import com.jiawa.wiki.util.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 荀彧 2021/5/17
 * 分类 service
 */
@Service
@Slf4j
public class CategoryService {

    @Resource
    private CategoryMapper mapper;

    @Resource
    private SnowFlake snowFlake;

    /**
     * 查询categorys
     * @param req
     * @return
     */
    public PageResp<CategoryQueryResp> list(CategoryQueryReq req) {
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        // 分页
        PageHelper.startPage(req.getPage(),req.getSize());
        List<Category> categorys = mapper.selectByExample(categoryExample);
        PageInfo<Category> info = new PageInfo<>(categorys);
        log.info("总条数:{}",info.getTotal());
        log.info("总页数:{}",info.getPageNum());
        PageResp<CategoryQueryResp> resp = new PageResp<>();
        resp.setTotal(info.getTotal());
        resp.setList(CopyUtil.copyList(categorys, CategoryQueryResp.class));
        return resp;
    }

    public void save(CategorySaveReq saveReq) {
        Category category = CopyUtil.copy(saveReq,Category.class);
        if (ObjectUtils.isEmpty(saveReq.getId())) {
            category.setId(snowFlake.nextId());
            mapper.insertSelective(category);
        }else {
            mapper.updateByPrimaryKey(category);
        }
    }

    /**
     * 删除操作
     * @param id
     */
    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    /**
     * 展示所有
     * @param
     * @return
     */
    public PageResp<CategoryQueryResp> all() {
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        List<Category> categorys = mapper.selectByExample(categoryExample);
        PageResp<CategoryQueryResp> resp = new PageResp<>();
        resp.setTotal(categorys.size());
        resp.setList(CopyUtil.copyList(categorys, CategoryQueryResp.class));
        return resp;
    }
}

